package reviewAlgorithms.binarySearch;

public class MySqrt {
    public static void main(String[] args) {
        int num = Integer.MAX_VALUE;
        System.out.println(mySqrt(num));
    }
    public static int mySqrt(int num){
        if (num < 0){
            return -1;
        }
        int left = 0;
        int right = num;
        int center;
        int ans = -1;
        while (left <= right){
            center = (left + right)/2;
            long temp = (long) center * center;
            if (temp <= num) {
                ans = center;
                left = center + 1;
            }else{
                right = center - 1;
            }
        }
        return ans;
    }

    public static int mySqrt1(int x) {
        if (x < 0){
            return -1;
        }
        int l = 0, r = x, ans = -1;
        while (l <= r) {
            int mid = l + (r - l) / 2;
            if ((long)mid * mid <= x) {
                ans = mid;
                l = mid + 1;
            }
            else {
                r = mid - 1;
            }
        }
        return ans;
    }
}
